String.prototype.format = function () {
    var args = arguments;
    var bool = $.isArray(args[0]);
    return this.replace(/\{(\d+)\}/g, function (m, n) {
        return bool ? args[0][n] : args[n];
    });
};

let $conf = require('./conf/commonConf');
let baseUrl=$conf.baseUrl;
let baseUrlApp=$conf.baseUrlApp;

let http=require('http');
let url=require('url');
let qs=require('querystring');
let express = require('express');
let path = require('path');
//自定义网页的logo
let favicon = require('serve-favicon');
//用于记录访问日志
let FileStreamRotator=require('file-stream-rotator');
let morgan = require('morgan');
let logDirectory=path.join(__dirname,'log');

let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let session=require('express-session');
let randomstring=require('randomstring');
let redisStore=require('connect-redis')(session);
let personalRouter=require('./routes/personalRouter');

let nunjucks=require('nunjucks');

let app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(randomstring.generate(128)));
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req,res,next){
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next()
});

// 输出日志到目录
var fs = require('fs');
fs.existsSync(logDirectory)||fs.mkdirSync(logDirectory);
morgan.token('date', function() {
    var p = new Date().toString().replace(/[A-Z]{3}\+/,'+').split(/ /);
    return( p[2]+'/'+p[1]+'/'+p[3]+':'+p[4]+' '+p[5] );
});
var accessLogStream=FileStreamRotator.getStream({
  date_formate:'YYYYMMDD',
  filename:path.join(logDirectory,'access-%DATE%.log'),
  frequency:'daily',
  verbose:false
});

app.use(morgan('combined',{stream:accessLogStream}));
app.use(baseUrl,personalRouter);

// Normalize a port into a number, string, or false.
function normalizePort(val){
  var port = parseInt(val, 10);
  if(isNaN(port)){
    return val;
  }
  if(port >= 0){
    return port;
  }
  return false;
}

let debug=require('debug')('demo:server');
let port =normalizePort(process.env.PORT||$conf.PORT);

app.set('port',port);

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

app.get(baseUrl+'demo.html',function(req, res) {
  res.render('demo.html');
});

function onError(error){
  if(error.syscall!=='listen'){
    throw error;
  }

  var bind=typeof port==='string'?'Pipe '+port:'Port '+port;
  switch(error.code){
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind+' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

function onListening(){
  var addr=server.address();
  var bind=typeof addr === 'string' ? 'pipe '+addr:'port '+ addr.port;
  debug('Listening on ' + bind);
}

// Create HTTP server
var server=http.createServer(app);
server.listen(port);
server.on('error',onError);
server.on('listening',onListening);

module.exports = app;
